{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "X4cRE8IbIrIV"
   },
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets. Uncomment the following cell and run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "MOsHUjgdIrIW",
    "outputId": "f84a093e-147f-470e-aad9-80fb51193c8e"
   },
   "outputs": [],
   "source": [
    "#! pip install transformers\n",
    "#! pip install datasets\n",
    "#! pip install huggingface_hub"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you're opening this notebook locally, make sure your environment has an install from the latest version of those libraries.\n",
    "\n",
    "To be able to share your model with the community and generate results like the one shown in the picture below via the inference API, there are a few more steps to follow.\n",
    "\n",
    "First you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then run the following cell and input your token:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import notebook_login\n",
    "\n",
    "notebook_login()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then you need to install Git-LFS and setup Git if you haven't already. Uncomment the following instructions and adapt with your name and email:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !apt install git-lfs\n",
    "# !git config --global user.email \"you@example.com\"\n",
    "# !git config --global user.name \"Your Name\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Make sure your version of Transformers is at least 4.16.0 since some of the functionality we use was only introduced in that version."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import transformers\n",
    "\n",
    "print(transformers.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HFASsisvIrIb"
   },
   "source": [
    "You can find a script version of this notebook to fine-tune your model in a distributed fashion using multiple GPUs or TPUs [here](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a3KD3WXU3l-O"
   },
   "source": [
    "# Fine-tuning a language model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JAscNNUD3l-P"
   },
   "source": [
    "In this notebook, we'll see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model on a language modeling task. We will cover two types of language modeling tasks which are:\n",
    "\n",
    "- Causal language modeling: the model has to predict the next token in the sentence (so the labels are the same as the inputs shifted to the right). To make sure the model does not cheat, its attention computations are masked so that tokens cannot attend to tokens to their right, as this would result in label leakage.\n",
    "\n",
    "![Widget inference representing the causal language modeling task](images/causal_language_modeling.png)\n",
    "\n",
    "- Masked language modeling: the model has to predict some tokens that are masked in the input. It still has access to the whole sentence, so it can use the tokens before and after the masked tokens to predict their value.\n",
    "\n",
    "![Widget inference representing the masked language modeling task](images/masked_language_modeling.png)\n",
    "\n",
    "We will see how to easily load and preprocess the dataset for each one of those tasks, and how to use Keras to fine-tune a model on it.\n",
    "\n",
    "A script version of this notebook you can directly run on a distributed environment or on TPU is available in our [examples folder](https://github.com/huggingface/transformers/tree/master/examples)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1r_n9OWV3l-Q"
   },
   "source": [
    "## Preparing the dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kswRMhPc3l-Q"
   },
   "source": [
    "For each of those tasks, we will use the [Wikitext 2]() dataset as an example. You can load it very easily with the 🤗 Datasets library."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "n2ZRs1cL3l-R",
    "outputId": "11151c56-be90-4d11-e7df-db85e745ca5c"
   },
   "outputs": [],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "datasets = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f1-9jepM3l-W"
   },
   "source": [
    "You can replace the dataset above with any dataset hosted on [the hub](https://huggingface.co/datasets) or use your own files. Just uncomment the following cell and replace the paths with your own input files:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "uxSaGa_l3l-W"
   },
   "outputs": [],
   "source": [
    "# datasets = load_dataset(\"text\", data_files={\"train\": path_to_train.txt, \"validation\": path_to_validation.txt}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jY1SwIrY3l-a"
   },
   "source": [
    "You can also load datasets from a csv or a JSON file, see the [full documentation](https://huggingface.co/docs/datasets/loading_datasets.html#from-local-files) for more information."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "u3EtYfeHIrIz"
   },
   "source": [
    "To access an actual element, you need to select a split first, then give an index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "X6HrpprwIrIz",
    "outputId": "d7670bc0-42e4-4c09-8a6a-5c018ded7d95"
   },
   "outputs": [],
   "source": [
    "datasets[\"train\"][10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WHUmphG3IrI3"
   },
   "source": [
    "To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ur5sNUcZ3l-g"
   },
   "outputs": [],
   "source": [
    "from datasets import ClassLabel\n",
    "import random\n",
    "import pandas as pd\n",
    "from IPython.display import display, HTML\n",
    "\n",
    "\n",
    "def show_random_elements(dataset, num_examples=10):\n",
    "    assert num_examples <= len(\n",
    "        dataset\n",
    "    ), \"Can't pick more elements than there are in the dataset.\"\n",
    "    picks = []\n",
    "    for _ in range(num_examples):\n",
    "        pick = random.randint(0, len(dataset) - 1)\n",
    "        while pick in picks:\n",
    "            pick = random.randint(0, len(dataset) - 1)\n",
    "        picks.append(pick)\n",
    "\n",
    "    df = pd.DataFrame(dataset[picks])\n",
    "    for column, typ in dataset.features.items():\n",
    "        if isinstance(typ, ClassLabel):\n",
    "            df[column] = df[column].transform(lambda i: typ.names[i])\n",
    "    display(HTML(df.to_html()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1Uk8NROQ3l-k",
    "outputId": "a822dcec-51e3-4dba-c73c-dba9e0301726"
   },
   "outputs": [],
   "source": [
    "show_random_elements(datasets[\"train\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CKerdF353l-o"
   },
   "source": [
    "As we can see, some of the texts are a full paragraph of a Wikipedia article while others are just titles or empty lines."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JEA1ju653l-p"
   },
   "source": [
    "## Causal Language modeling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "v5GTGKZS3l-q"
   },
   "source": [
    "For causal language modeling (CLM) we are going to take all the texts in our dataset, tokenize them and concatenate them. Then we will split them into examples of a fixed sequence length. This way the model will receive chunks of contiguous text that may look like:\n",
    "```\n",
    "part of text 1\n",
    "```\n",
    "or \n",
    "```\n",
    "end of text 1 [BOS_TOKEN] beginning of text 2\n",
    "```\n",
    "depending on whether they span multiple original texts or not. The labels will be the same as the inputs, shifted to the right.\n",
    "\n",
    "We will use the [`distilgpt2`](https://huggingface.co/distilgpt2) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=causal-lm) instead:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "-WGBCO343l-q"
   },
   "outputs": [],
   "source": [
    "model_checkpoint = \"distilgpt2\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5io6fY_d3l-u"
   },
   "source": [
    "To tokenize all our texts with the same vocabulary that was used when training the model, we have to download a pretrained tokenizer. This is all done by the `AutoTokenizer` class:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "iAYlS40Z3l-v"
   },
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rpOiBrJ13l-y"
   },
   "source": [
    "We can now call the tokenizer on all our texts. This is very simple, using the [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map) method from the Datasets library. First we define a function that calls the tokenizer on our texts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "lS2m25YM3l-z"
   },
   "outputs": [],
   "source": [
    "def tokenize_function(examples):\n",
    "    return tokenizer(examples[\"text\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "M9xVAa3s3l-2"
   },
   "source": [
    "Then we apply it to all the splits in our `datasets` object, using `batched=True` and 4 processes to speed up the preprocessing. We won't need the `text` column afterward, so we discard it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "NVAO0H8u3l-3",
    "outputId": "30d88b8a-e353-4e13-f709-8e5e06ef747b"
   },
   "outputs": [],
   "source": [
    "tokenized_datasets = datasets.map(\n",
    "    tokenize_function, batched=True, num_proc=4, remove_columns=[\"text\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8qik3J_C3l-7"
   },
   "source": [
    "If we now look at an element of our datasets, we will see the text have been replaced by the `input_ids` the model will need:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "nYv_mcKk3l-7",
    "outputId": "8334734c-0f86-4e18-ec17-4216a2d5dd18"
   },
   "outputs": [],
   "source": [
    "tokenized_datasets[\"train\"][1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "obvgcXda3l--"
   },
   "source": [
    "Now for the harder part: We need to concatenate all our texts together, and then split the result into chunks of a fixed size, which we will call `block_size`. To do this, we will use the `map` method again, with the option `batched=True`. When we use `batched=True`, the function we pass to `map()` will be passed multiple inputs at once, allowing us to group them into more or fewer examples than we had in the input. This allows us to create our new fixed-length samples.\n",
    "\n",
    "We can use any `block_size` up to the maximum length our model was pretrained with, which for models in the `gpt2` family is usually something in the range 512-1024. This might be a bit too big to fit in your GPU RAM, though, so let's use something a bit smaller: 128."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "DVHs5aCA3l-_"
   },
   "outputs": [],
   "source": [
    "# block_size = tokenizer.model_max_length\n",
    "block_size = 128"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RpNfGiMw3l_A"
   },
   "source": [
    "Then we write the preprocessing function that will group our texts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "iaAJy5Hu3l_B"
   },
   "outputs": [],
   "source": [
    "def group_texts(examples):\n",
    "    # Concatenate all texts.\n",
    "    concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n",
    "    total_length = len(concatenated_examples[list(examples.keys())[0]])\n",
    "    # We drop the small remainder, though you could add padding instead if the model supports it\n",
    "    # In this, as in all things, we advise you to follow your heart\n",
    "    total_length = (total_length // block_size) * block_size\n",
    "    # Split by chunks of max_len.\n",
    "    result = {\n",
    "        k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n",
    "        for k, t in concatenated_examples.items()\n",
    "    }\n",
    "    result[\"labels\"] = result[\"input_ids\"].copy()\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LGJWXtNv3l_C"
   },
   "source": [
    "Note that we duplicate the inputs for our labels, without shifting them, even though we told you the labels need to be shifted! This is because CausalLM models in the 🤗 Transformers library automatically apply right-shifting to the inputs, so we don't need to do it manually.\n",
    "\n",
    "Also note that by default, the `map` method will send a batch of 1,000 examples to be treated by the preprocessing function. So here, we will drop the remainder to make the concatenated tokenized texts a multiple of `block_size` every 1,000 examples. You can adjust this behavior by passing a higher batch size (which will also be processed slower). You can also speed-up the preprocessing by using multiprocessing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "gXUSfBrq3l_C",
    "outputId": "34e55885-3d8f-4f05-cbdb-706ce56a25f8"
   },
   "outputs": [],
   "source": [
    "lm_datasets = tokenized_datasets.map(\n",
    "    group_texts,\n",
    "    batched=True,\n",
    "    batch_size=1000,\n",
    "    num_proc=4,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6n84V8Gc3l_G"
   },
   "source": [
    "And we can check our datasets have changed: now the samples contain chunks of `block_size` contiguous tokens, potentially spanning several of our original texts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "hTeGCLl_3l_G",
    "outputId": "ab381a07-f92e-4b14-f7b6-e4af5513d7c4"
   },
   "outputs": [],
   "source": [
    "tokenizer.decode(lm_datasets[\"train\"][1][\"input_ids\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iEmeQ7Xm3l_H"
   },
   "source": [
    "Now that the data has been cleaned, we're ready to initialize our model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "sPqQA3TT3l_I"
   },
   "outputs": [],
   "source": [
    "from transformers import TFAutoModelForCausalLM\n",
    "\n",
    "model = TFAutoModelForCausalLM.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "VyPQTOF_3l_J"
   },
   "source": [
    "Once we've done that, it's time for our optimizer! We can initialize our `AdamWeightDecay` optimizer directly, or we can use the [`create_optimizer`](https://huggingface.co/docs/transformers/main_classes/optimizer_schedules#transformers.create_optimizer) function to generate an `AdamWeightDecay` optimizer with a learning rate schedule. In this case, we'll just stick with a constant learning rate for simplicity, so let's just use `AdamWeightDecay`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "jElf8LJ33l_K"
   },
   "outputs": [],
   "source": [
    "from transformers import create_optimizer, AdamWeightDecay"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "YbSwEhQ63l_L"
   },
   "outputs": [],
   "source": [
    "optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we compile our model. Note that most Transformers models compute loss internally, so we actually don't have to specify anything for that argument! You can of course set your own loss function if you want, but by default our models will choose the 'obvious' loss that matches their task, such as cross-entropy in the case of language modelling. The built-in loss will also correctly handle things like masking the loss on padding tokens, or unlabelled tokens in the case of masked language modelling, so we recommend using it unless you're an advanced user!\n",
    "\n",
    "We also use the `jit_compile` argument to compile the model with [XLA](https://www.tensorflow.org/xla). XLA compilation adds a delay at the start of training, but this is quickly repaid by faster training iterations after that. It has one downside, though - if the shape of your input changes at all, then it will need to rerun the compilation again! This isn't a problem for us in this notebook, because all of our examples are exactly the same length. Be careful with it when that isn't true, though - if you have a variable sequence length in your batches, then you might spend more time compiling your model than actually training, especially for small datasets!\n",
    "\n",
    "If you encounter difficulties when training with XLA, it's a good idea to remove the `jit_compile` argument and see if that fixes things. In fact, when debugging, it can be helpful to skip graph compilation entirely with the `run_eagerly=True` argument to [`compile()`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#compile). This will let you identify the exact line of code where problems arise, but it will significantly reduce your performance, so make sure to remove it again when you've fixed the problem!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "model.compile(optimizer=optimizer, jit_compile=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sZRbT9ui3l_N"
   },
   "source": [
    "Next, we convert our datasets to `tf.data.Dataset`, which Keras understands natively. There are two ways to do this - we can use the slightly more low-level [`Dataset.to_tf_dataset()`](https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.to_tf_dataset) method, or we can use [`Model.prepare_tf_dataset()`](https://huggingface.co/docs/transformers/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset). The main difference between these two is that the `Model` method can inspect the model to determine which column names it can use as input, which means you don't need to specify them yourself. It also supplies a data collator by default which is appropriate for most tasks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "OEuqwIra3l_N"
   },
   "outputs": [],
   "source": [
    "train_set = model.prepare_tf_dataset(\n",
    "    lm_datasets[\"train\"],\n",
    "    shuffle=True,\n",
    "    batch_size=16,\n",
    ")\n",
    "\n",
    "validation_set = model.prepare_tf_dataset(\n",
    "    lm_datasets[\"validation\"],\n",
    "    shuffle=False,\n",
    "    batch_size=16,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6Vvz34Td3l_O"
   },
   "source": [
    "Now we can train our model. We can also add a callback to sync up our model with the Hub - this allows us to resume training from other machines and even test the model's inference quality midway through training! If you don't want to do this, simply remove the callbacks argument in the call to `fit()`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "NyZvu_MF3l_P",
    "outputId": "b69d0931-7f1f-4f2d-fdb8-09d37c7418bb"
   },
   "outputs": [],
   "source": [
    "from transformers.keras_callbacks import PushToHubCallback\n",
    "from tensorflow.keras.callbacks import TensorBoard\n",
    "\n",
    "model_name = model_checkpoint.split(\"/\")[-1]\n",
    "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n",
    "\n",
    "tensorboard_callback = TensorBoard(log_dir=\"./clm_model_save/logs\")\n",
    "\n",
    "push_to_hub_callback = PushToHubCallback(\n",
    "    output_dir=\"./clm_model_save\",\n",
    "    tokenizer=tokenizer,\n",
    "    hub_model_id=push_to_hub_model_id,\n",
    ")\n",
    "\n",
    "callbacks = [tensorboard_callback, push_to_hub_callback]\n",
    "\n",
    "model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=callbacks)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3APq-vUc3l_R"
   },
   "source": [
    "Once the training is completed, we can evaluate our model and get its cross-entropy loss on the validation set like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "diKZnB1I3l_R",
    "outputId": "9b3ac725-0117-4830-f380-a555ee57c8cf"
   },
   "outputs": [],
   "source": [
    "eval_loss = model.evaluate(validation_set)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The quality of language models is often measured in 'perplexity' rather than cross-entropy. To convert to perplexity, we simply raise e to the power of the cross-entropy loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "print(f\"Perplexity: {math.exp(eval_loss):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you saved the model with the callback, you can now share this model with all your friends, family, favorite pets: they can all load it with the identifier `\"your-username/the-name-you-picked\"` so for instance:\n",
    "\n",
    "```python\n",
    "from transformers import AutoModelForCausalLM\n",
    "\n",
    "model = AutoModelForCausalLM.from_pretrained(\"sgugger/my-awesome-model\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inference"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we've trained our model, let's see how we could load it and use it to generate text in future! First, let's load it from the hub. This means we can resume the code from here without needing to rerun everything above every time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, TFAutoModelForCausalLM\n",
    "\n",
    "# You can, of course, use your own username and model name here \n",
    "# once you've pushed your model using the code above!\n",
    "checkpoint = \"Rocketknight1/distilgpt2-finetuned-wikitext2\"\n",
    "model = TFAutoModelForCausalLM.from_pretrained(checkpoint)\n",
    "tokenizer = AutoTokenizer.from_pretrained(checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's make up a sentence and see if the model can continue it for us!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_sentence = \"The Gulf War was a conflict between\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll need to tokenize our input(s) and then use the `generate()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenized = tokenizer(test_sentence, return_tensors=\"np\")\n",
    "\n",
    "outputs = model.generate(**tokenized, max_length=24)\n",
    "\n",
    "print(outputs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Those are definitely tokens! We should probably turn them back into text so that we can read them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer.decode(outputs[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This combination of quick, fluent responses with a complete incomprehension of the actual underlying facts will be familiar to anyone who's ever scrolled through their Twitter timeline. `distilgpt2` is a very small LM compared to some others, and as you scale them up and train them for longer on larger datasets to get lower losses they often stop making errors as obvious as this one, but their tendency to confidently hallucinate their own \"alternative facts\" rather than admit ignorance never fully goes away, so bear this in mind before you deploy a generative language model in production!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pipeline API"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An alternative way to quickly perform inference with any model on the hub is to use the [Pipeline API](https://huggingface.co/docs/transformers/main_classes/pipelines), which abstracts away all the steps we did manually above. It will perform the preprocessing, forward pass and postprocessing all in a single object.\n",
    "\n",
    "Let's showcase this for our trained model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "text_generator = pipeline(\n",
    "    \"text-generation\", \n",
    "    \"Rocketknight1/distilgpt2-finetuned-wikitext2\",\n",
    "    framework=\"tf\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_generator(test_sentence)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that we got a different (and equally historically, uh, interesting) response this time! Because [`generate()`](https://huggingface.co/docs/transformers/v4.20.1/en/main_classes/text_generation#transformers.generation_tf_utils.TFGenerationMixin.generate) samples from the model's probability outputs each time, it can return multiple different outputs from the same starting text. If consistency is important to you, you can use parameters like `temperature` to control how variable the outputs should be."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "q-EIELH43l_T"
   },
   "source": [
    "## Masked language modeling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LWk97-Ny3l_T"
   },
   "source": [
    "For masked language modeling (MLM) we are going to use the same preprocessing as before for our dataset with one additional step: we will randomly mask some tokens (by replacing them by `[MASK]`) and the labels will be adjusted to only include the masked tokens (we don't have to predict the non-masked tokens).\n",
    "\n",
    "We will use the [`distilroberta-base`](https://huggingface.co/distilroberta-base) model for this example. You can pick any of the checkpoints listed [here](https://huggingface.co/models?filter=masked-lm) instead:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "QRTpmyCc3l_T"
   },
   "outputs": [],
   "source": [
    "model_checkpoint = \"distilroberta-base\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "12F1ulgT3l_V"
   },
   "source": [
    "We can apply the same tokenization function as before, we just need to update our tokenizer to use the checkpoint we just picked. Don't panic about the warnings about inputs being too long for the model - remember that we'll be breaking them into shorter chunks right afterwards!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "h8RCYcvr3l_V",
    "outputId": "a5ffeb0a-71da-4b27-e57a-c62f1927562e"
   },
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n",
    "tokenized_datasets = datasets.map(\n",
    "    tokenize_function, batched=True, num_proc=4, remove_columns=[\"text\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "MTuy8UUs3l_X"
   },
   "source": [
    "And now, we group texts together and chunk them into samples of length `block_size`. You can skip this step if your dataset is composed of individual sentences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "LVYPMwEs3l_X",
    "outputId": "e71ed7f1-b182-4643-a8fb-3d731c70e40b"
   },
   "outputs": [],
   "source": [
    "lm_datasets = tokenized_datasets.map(\n",
    "    group_texts,\n",
    "    batched=True,\n",
    "    batch_size=1000,\n",
    "    num_proc=4,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "nFJ49iHJ3l_Z"
   },
   "source": [
    "The rest is very similar to what we had, with two exceptions. First we use a model suitable for masked LM:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "PM10A9Za3l_Z",
    "outputId": "fff2d5bb-397d-4d5d-9aa9-933090cb6680"
   },
   "outputs": [],
   "source": [
    "from transformers import TFAutoModelForMaskedLM\n",
    "\n",
    "model = TFAutoModelForMaskedLM.from_pretrained(model_checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We redefine our `optimizer` as we did with the CLM model, and we compile the model. We're using the internal loss and `jit_compile` again, like we did before."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import create_optimizer, AdamWeightDecay\n",
    "import tensorflow as tf\n",
    "\n",
    "optimizer = AdamWeightDecay(lr=2e-5, weight_decay_rate=0.01)\n",
    "\n",
    "model.compile(optimizer=optimizer, jit_compile=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "z6uuUnvz3l_b"
   },
   "source": [
    "Finally, we use a special `data_collator`. The `data_collator` is a function that is responsible for taking the samples and batching them in tensors. In the previous example, we had nothing special to do, so we just used the default for this argument. Here we want to randomly mask tokens. We could do it as a pre-processing step (like the tokenization) but then the tokens would always be masked the same way at each epoch. By doing this step inside the `data_collator`, we ensure this random masking is done in a new way each time we go over the data.\n",
    "\n",
    "To do this masking for us, the library provides a `DataCollatorForLanguageModeling`. We can adjust the probability of the masking. Note that our data collators are designed to work for multiple frameworks, so ensure you set the `return_tensors='np'` argument to get NumPy arrays out - you don't want to accidentally get a load of `torch.Tensor` objects in the middle of your nice TF code! You could also use `return_tensors='tf'` to get TensorFlow tensors, but our TF dataset pipeline actually uses a NumPy loader internally, which is wrapped at the end with a `tf.data.Dataset`. As a result, `np` is usually more reliable and performant when you're using it!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "nRZ-5v_P3l_b"
   },
   "outputs": [],
   "source": [
    "from transformers import DataCollatorForLanguageModeling\n",
    "\n",
    "data_collator = DataCollatorForLanguageModeling(\n",
    "    tokenizer=tokenizer, mlm_probability=0.15, return_tensors=\"np\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bqHnWcYC3l_d"
   },
   "source": [
    "Now we generate our datasets as before. Remember to pass the `data_collator` you just made to the `collate_fn` argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_set = model.prepare_tf_dataset(\n",
    "    lm_datasets[\"train\"],\n",
    "    shuffle=True,\n",
    "    batch_size=16,\n",
    "    collate_fn=data_collator,\n",
    ")\n",
    "\n",
    "validation_set = model.prepare_tf_dataset(\n",
    "    lm_datasets[\"validation\"],\n",
    "    shuffle=False,\n",
    "    batch_size=16,\n",
    "    collate_fn=data_collator,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now we fit our model! As before, we can use a callback to sync with the hub during training. You can remove this if you don't want to!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "V-Y3gNqV3l_d"
   },
   "outputs": [],
   "source": [
    "from transformers.keras_callbacks import PushToHubCallback\n",
    "\n",
    "model_name = model_checkpoint.split(\"/\")[-1]\n",
    "push_to_hub_model_id = f\"{model_name}-finetuned-wikitext2\"\n",
    "\n",
    "callback = PushToHubCallback(\n",
    "    output_dir=\"./mlm_model_save\",\n",
    "    tokenizer=tokenizer,\n",
    "    hub_model_id=push_to_hub_model_id,\n",
    ")\n",
    "\n",
    "model.fit(train_set, validation_data=validation_set, epochs=1, callbacks=[callback])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KDBi0reX3l_g"
   },
   "source": [
    "Like before, we can evaluate our model on the validation set and compute perplexity. The perplexity is much lower than for the CLM objective because for the MLM objective, we only have to make predictions for the masked tokens (which represent 15% of the total here) while having access to the rest of the tokens. It's thus an easier task for the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "4hSaANqj3l_g",
    "outputId": "eeeb8727-2e27-4aeb-ac71-c98123214661"
   },
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "eval_results = model.evaluate(validation_set)\n",
    "print(f\"Perplexity: {math.exp(eval_results):.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you used the callback, you can now share this model with all your friends, family or favorite pets: they can all load it with the identifier `\"your-username/the-name-you-picked\"` so for instance:\n",
    "\n",
    "```python\n",
    "from transformers import AutoModelForMaskedLM\n",
    "\n",
    "model = AutoModelForMaskedLM.from_pretrained(\"your-username/my-awesome-model\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inference"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Masked language models are not generally used directly for inference - the task they were trained on was to \"fill in the blank\", to identify missing words in sentences, and while this is an interesting demo, it has limited uses in production! However, masked language models work great as a base to be fine-tuned further on new tasks, like text or token classification. They are generally preferable to causal language models as a base for tasks that do not involve generating new text, and you'll see them being used as a base model in several other notebooks in this folder.\n",
    "\n",
    "Still, if you're curious, you can do inference to see what your model learned! Let's use the `fill-mask` pipeline and give the model some test sentences. Note that the mask token may not be \"\\<mask>\" in some other models - you can use `tokenizer.mask_token` to find out what it is for your specific model if you're not using `distilroberta`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "# You can of course use your own model checkpoint here instead of mine\n",
    "mask_filler = pipeline(\n",
    "    \"fill-mask\", \n",
    "    \"Rocketknight1/distilroberta-base-finetuned-wikitext2\",\n",
    "    framework=\"tf\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mask_filler(\"The most common household pets are <mask> and dogs.\", top_k=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nice! Let's see how it does on history:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mask_filler(\"The Gulf War was a conflict that took place in <mask> in 1990-1991.\", top_k=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Masked language models are often more accurate than causal language models because they can use information that comes after the masked position to help them, whereas causal models can only look back. This answer is definitely better than the answers from the causal LM above!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "name": "Fine-tune a language model",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
